'''

Case Type： 数据库系统
Case Name： 事务操作时人为删除日志文件，不影响数据库运行
Create At:  2020/06/23
@zou_jialiang0505328126
Descption:  1.执行TPCC事务2.在事务执行过程中删除log文件

history：
created： 2020/06/23  created by @wan005
'''
import os
import unittest
import sys
import time
from yat.test import Node
from yat.test import macro

sys.path.append(sys.path[0] + "/../")
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import *
from testcase.utils.Common import Common
from testcase.utils.ComThread import *
from testcase.utils.Constant import *


class DelPglog(unittest.TestCase):
    sh = CommonSH()
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info('------------Opengauss_Reliability_Dbsys_Case049.py start------------')
        self.rootNode = Node()
        self.dbUserNode = Node(node='dbuser')
        self.DN_NODE_NAME = macro.DN_NODE_NAME
        self.PG_LOG_PATH = macro.PG_LOG_PATH
        self.TPCC_PATH = macro.TPCC_PATH
        self.com = Common()
        self.Constant = Constant()

    def test_del_pglog(self):
        tpcc_thread = ComThread(self.com.startTPCC, args=(self.rootNode, self.TPCC_PATH,))
        tpcc_thread.start()
        time.sleep(5)

        # delete pg_log : replace rm -rf with mv, avoid db crushing, when issue happens we can use bak file to recover
        self.log.info("delete pg_log")
        pg_log_filename = self.com.getlatestPglog(self.dbUserNode, self.PG_LOG_PATH, self.DN_NODE_NAME)
        self.log.info(pg_log_filename)
        deletefil_cmd = "mv " + self.PG_LOG_PATH + '/' + self.DN_NODE_NAME + '/' + pg_log_filename + ' ' + self.PG_LOG_PATH + '/' + self.DN_NODE_NAME + '/' + pg_log_filename + '.baktest'
        self.log.info(deletefil_cmd)
        deletefil_msg = self.rootNode.sh(deletefil_cmd).result()
        self.log.info(deletefil_msg)

        tpcc_thread.join(timeout=int(macro.TPCC_RUN_MAX_TIME) * 2)

        tpcc_result = tpcc_thread.get_result()
        self.log.info(tpcc_result)
        self.assertIn(self.Constant.TPCC_SUCCESS_MSG, tpcc_result)

    def tearDown(self):
        self.log.info('this is tearDown')
        self.log.info('recover pglog')
        filename = self.com.getlatestPglog(self.dbUserNode, self.PG_LOG_PATH, self.DN_NODE_NAME)
        self.log.info(filename)
        orig_pg_log_filename = filename.rsplit(".", 1)[0]
        self.log.info(orig_pg_log_filename)
        recoverfil_cmd = "mv " + self.PG_LOG_PATH + '/' + self.DN_NODE_NAME + '/' + filename + ' ' + self.PG_LOG_PATH + '/' + self.DN_NODE_NAME + '/' + orig_pg_log_filename
        self.log.info(recoverfil_cmd)
        msg = self.rootNode.sh(recoverfil_cmd).result()
        self.log.info(msg)
